/**
 * 尊敬的用户，你好：页面 JS 面板是高阶用法，一般不建议普通用户使用，如需使用，请确定你具备研发背景，能够自我排查问题。
 * 我们可以用 JS 面板来开发一些定制度高功能，比如：调用API接口，自定义动作执行等等。
 */

// 当页面渲染完毕后马上调用下面的函数，这个函数是在当前页面 - 设置 - 生命周期 - 页面加载完成时中被关联的。
export function didMount() {
    ("「页面 JS」：当前页面地址 " + location.href);
}

export function valueChange() {
    debugger
    const self = this;

    const unitIndustryTypeCodeValue = this.$$("single_select_s3i9c").$$getValue();
    const regionCodeValue = this.$$("text_input_54pt7r").$$getValue();

    const countryValue = self.$$("text_input_6iltos").cValue;
    const provinceValue = self.$$("text_input_e7ln66").cValue;
    const cityValue = self.$$("text_input_1x0udy").cValue;
    const districtValue = self.$$("text_input_55q4pw").cValue;
    const streetValue = self.$$("text_input_dd3dav").cValue;
    const communityValue = self.$$("text_input_ayzvd0").cValue;

    const params = [{
        name: "unitIndustryTypeCode",
        valueContent: unitIndustryTypeCodeValue
    }, {
        name: "regionCode",
        valueContent: regionCodeValue
    }];

    api.DATA_SOURCE_EXECUTE("ds_mod:f56cb3de-23a0-4950-8b0b-d781cf6cfedb", "ddcat", params, [], "").then(res => {
        const recCountData = res.result[0];
        // 初始化统计表单的值
        initLawRecCount(self, recCountData);
        api.DATA_SOURCE_EXECUTE("ds_mod:d0cfa966-44d9-40b2-ba11-5955971774fa", "ddcat", params, [], "").then(res => {
            const recTrendData = res.result;
            // 初始化折线图统计
            initLawRecTrend(self, recTrendData);
            api.DATA_SOURCE_EXECUTE("ds_mod:6d45742f-b3bb-407f-89bf-895f55ced12a", "ddcat", params, [], "").then(res => {
                const punishDecideTypeTotal = res.result;
                // 初始化行政处罚分布统计
                initpunishDecideTypeTotal(self, punishDecideTypeTotal);
                const paramsRegion = [{
                    name: "provinceId",
                    valueContent: provinceValue
                }, {
                    name: "cityId",
                    valueContent: cityValue
                }, {
                    name: "districtId",
                    valueContent: districtValue
                }, {
                    name: "streetId",
                    valueContent: streetValue
                }, {
                    name: "communityId",
                    valueContent: communityValue
                }, {
                    name: "countryId",
                    valueContent: countryValue
                }];

                api.DATA_SOURCE_EXECUTE("ds_mod:1fdea209-3c76-4a5a-b42d-fe452c208e19", "ddcat", paramsRegion, [], "").then(res => {
                    const penaltyJudgment = res.result;
                    // 初始化行政处罚研判
                    initPenaltyJudgment(self, penaltyJudgment);
                });
            });
        });


    });
}

function initPenaltyJudgment(self, penaltyJudgment) {
    // 更新统计数字
    updateField("Count", penaltyJudgment, "warnRecNum");
    // 更新名称字段
    updateField("Name", penaltyJudgment, "warn_item_name");
    // 更新规则ID（作为数据属性绑定）
    updateField("Card", penaltyJudgment, "rule_id", "data", "ruleId");
}


function updateField(suffix, data, dataKey, target = "text", attrName = "") {
    const prefixes = [
        "entityValidity", "procedureStandard", "evidenceQuality",
        "documentArchive", "discretionExercise", "enforcementImpact",
        "infoDisclosure", "integrityDiscipline"
    ];

    prefixes.forEach((prefix, index) => {
        const elementId = `${prefix}${suffix}`;
        const content = data[index][dataKey] + (target === "text" ? "" : "");
        updateAllElementsById(elementId, content, target, attrName);
    });
}


function updateAllElementsById(id, content, target = "text", attrName = "") {
    document.querySelectorAll(`[id="${id}"]`).forEach(element => {
        switch (target) {
            case "text":
                element.textContent = content;
                break;
            case "data":
                element.dataset[attrName] = content;
                break;
            case "attribute":
                element.setAttribute(attrName, content);
                break;
            default:
                element.textContent = content;
        }
    });
}

function initpunishDecideTypeTotal(self, punishDecideTypeTotal) {
    const punishDecideTypeTotalCategory1 = self.$$("zfyy_form_chart_category_cd39e5");
    const punishDecideTypeTotalCategory2 = self.$$("zfyy_form_chart_category_aqx419");

    const result1 = punishDecideTypeTotal.slice(0, 4).map((item) => {
        return {
            num: item.CODE,
            name: item.display_name,
            text: item.display_name,
            value: item.recNum,
            checked: false
        }
    });
    const result2 = punishDecideTypeTotal.slice(4, 8).map((item) => {
        return {
            num: item.CODE,
            name: item.display_name,
            text: item.display_name,
            value: item.recNum,
            checked: false
        }
    });
    punishDecideTypeTotalCategory1.data.props.dataSource.options = result1 || [];
    punishDecideTypeTotalCategory2.data.props.dataSource.options = result2 || [];


}

function initLawRecTrend(self, recTrendData) {
    const lawRecTrendLine = self.$$("zfyy_form_chart_line_553sls");
    recTrendData = (recTrendData && Array.isArray(recTrendData)) ? recTrendData : [];
    function createSeries(name, text, dataKey) {
        return {
            name: name,
            text: text,
            value: recTrendData.map(function(item) {
                return {
                    text: (item && item.stat_period) ? item.stat_period : "",
                    value: (item && item[dataKey] !== undefined) ? Number(item[dataKey]) : 0
                };
            }),
            checked: false
        };
    }

    let lawRecTrendLineData = [
        createSeries("general", "普通程序", "generalRecCount"),
        createSeries("simple", "简易程序", "simpleRecCount")
    ];

    if (lawRecTrendLine.data
        && lawRecTrendLine.data.props
        && lawRecTrendLine.data.props.dataSource) {
        lawRecTrendLine.data.props.dataSource.options = lawRecTrendLineData;
    } else {
        console.error("图表数据结构不完整");
    }

    lawRecTrendLine.data.props.dataSource.options = lawRecTrendLineData || []
}



function initLawRecCount(self, recCountData) {
    self.$$("text_4tx7kc").$$setValue(recCountData.punishRecNum + '');
    self.$$("text_gg923i").$$setValue(recCountData.simpleRecCount + '');
    self.$$("text_aur9jo").$$setValue(recCountData.generalRecCount + '');
}
